package com.lyl.activiti.demo.listener;

import com.lyl.activiti.demo.util.SendMailUtil;
import com.lyl.activiti.demo.util.SpringContextUtil;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.delegate.event.ActivitiEntityEvent;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.identity.User;
import org.activiti.engine.impl.persistence.entity.IdentityLinkEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.repository.ProcessDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.List;

/**
 * Created by lyl on 2014/5/13.
 */
public class EventListener implements ActivitiEventListener {

    @Override
    public void onEvent(ActivitiEvent event) {
        switch (event.getType()) {
            case TASK_ASSIGNED:
                //此处判断用户操作是否为被签收的人，若不是则通知被签收的人
                if(RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes){
                    //通过session获取当前操作用户
                    ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                    User operator = (User) requestAttributes.getRequest().getSession().getAttribute("user");

                    if(event instanceof ActivitiEntityEvent) {
                        TaskEntity entity = (TaskEntity) ((ActivitiEntityEvent) event).getEntity();
                        String assigneeId = entity.getAssignee();
                        if(!operator.getId().equals(assigneeId)) {
                            //操作员与被签收人不是一个人，发邮件通知被签收人
                            sendMail(entity, assigneeId);
                        }
                    }
                }
                break;
            case ENTITY_CREATED:
                if(event instanceof ActivitiEntityEvent){
                    if (((ActivitiEntityEvent)event).getEntity() instanceof IdentityLinkEntity){
                        IdentityLinkEntity identityLinkEntity = (IdentityLinkEntity) ((ActivitiEntityEvent) event).getEntity();
                        //此处是候选组，没有测试候选人呢
                        if ("candidate".equals(identityLinkEntity.getType())){
                            //发邮件通知候选人员去签收
                            sendMailSignFor(identityLinkEntity);
                        }
                    }
                }
                break;
        }
    }

    private void sendMailSignFor(IdentityLinkEntity identityLinkEntity) {
        ApplicationContext context = SpringContextUtil.getApplicationContext();
        SendMailUtil sendMail = new SendMailUtil(context);

        //获取待签收人的账户邮箱
        IdentityService identityService = (IdentityService) context.getBean("identityService");
        List<User> users = identityService.createUserQuery().memberOfGroup(identityLinkEntity.getGroupId()).list();

        //获取申请人id
        HistoryService historyService = (HistoryService) context.getBean("historyService");
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(identityLinkEntity.getTask().getProcessInstanceId()).singleResult();
        String apply = historicProcessInstance.getStartUserId();

        //获取流程定义
        RepositoryService repositoryService = (RepositoryService) context.getBean("repositoryService");
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(identityLinkEntity.getTask().getProcessDefinitionId()).singleResult();

        for (User user : users) {
            String text = "亲爱的"+user.getFirstName()+": 您有待签收任务了。  "+apply+"申请了\""+processDefinition.getName()+"\";  当前环节为："+identityLinkEntity.getTask().getName();//谁谁谁申请了什么什么
            sendMail.send(user.getEmail(),"待签收任务提醒",text);
        }
    }

    private void sendMail(TaskEntity entity, String assigneeId) {
        ApplicationContext context = SpringContextUtil.getApplicationContext();
        SendMailUtil sendMail = new SendMailUtil(context);

        //获取被签收人的账户邮箱
        IdentityService identityService = (IdentityService) context.getBean("identityService");
        User assignee = identityService.createUserQuery().userId(assigneeId).singleResult();

        //获取申请人id
        HistoryService historyService = (HistoryService) context.getBean("historyService");
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(entity.getProcessInstanceId()).singleResult();
        String apply = historicProcessInstance.getStartUserId();

        //获取流程定义
        RepositoryService repositoryService = (RepositoryService) context.getBean("repositoryService");
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(entity.getProcessDefinitionId()).singleResult();

        String text = "亲爱的"+assignee.getFirstName()+": 您有待办任务了。  "+apply+"申请了\""+processDefinition.getName()+"\";  当前环节为："+entity.getName();//谁谁谁申请了什么什么
        sendMail.send(assignee.getEmail(),"待办任务提醒",text);
    }

    @Override
    public boolean isFailOnException() {
        // isFailOnException()方法决定了当事件分发时，onEvent(..)方法抛出异常时的行为。 这里返回的是false，会忽略异常
        return false;
    }
}
